'use client';

import { useState, useCallback } from 'react';

export default function PtzAdvanced({ 
  channelId, 
  deviceId,
  ptzApi,
  onLog,
  disabled = false 
}) {
  const [activeTab, setActiveTab] = useState('cruise');
  const [cruiseSettings, setCruiseSettings] = useState({
    cruiseId: 1,
    speed: 100,
    time: 5
  });
  const [scanSettings, setScanSettings] = useState({
    scanId: 1,
    speed: 100
  });
  const [auxiliarySettings, setAuxiliarySettings] = useState({
    switchId: 1,
    command: 'on'
  });

  // 巡航控制
  const handleCruiseControl = useCallback(async (action) => {
    if (!ptzApi || disabled) return;

    try {
      const { cruiseId, speed, time } = cruiseSettings;
      let result;

      switch (action) {
        case 'setSpeed':
          result = await ptzApi.setCruiseSpeed(deviceId, channelId, cruiseId, speed);
          onLog?.(`设置巡航速度: ${speed}`);
          break;
        case 'setTime':
          result = await ptzApi.setCruiseTime(deviceId, channelId, cruiseId, time);
          onLog?.(`设置巡航时间: ${time}秒`);
          break;
        case 'start':
          result = await ptzApi.startCruise(deviceId, channelId, cruiseId);
          onLog?.(`开始巡航: 组${cruiseId}`);
          break;
        case 'stop':
          result = await ptzApi.stopCruise(deviceId, channelId, cruiseId);
          onLog?.(`停止巡航: 组${cruiseId}`);
          break;
        default:
          break;
      }
    } catch (error) {
      onLog?.(`巡航控制失败: ${error.message}`);
    }
  }, [ptzApi, deviceId, channelId, cruiseSettings, onLog, disabled]);

  // 扫描控制
  const handleScanControl = useCallback(async (action) => {
    if (!ptzApi || disabled) return;

    try {
      const { scanId, speed } = scanSettings;
      let result;

      switch (action) {
        case 'setSpeed':
          result = await ptzApi.setSpeedForScan(deviceId, channelId, scanId, speed);
          onLog?.(`设置扫描速度: ${speed}`);
          break;
        case 'setLeft':
          result = await ptzApi.setLeftForScan(deviceId, channelId, scanId);
          onLog?.(`设置扫描左边界: 组${scanId}`);
          break;
        case 'setRight':
          result = await ptzApi.setRightForScan(deviceId, channelId, scanId);
          onLog?.(`设置扫描右边界: 组${scanId}`);
          break;
        case 'start':
          result = await ptzApi.startScan(deviceId, channelId, scanId);
          onLog?.(`开始扫描: 组${scanId}`);
          break;
        case 'stop':
          result = await ptzApi.stopScan(deviceId, channelId, scanId);
          onLog?.(`停止扫描: 组${scanId}`);
          break;
        default:
          break;
      }
    } catch (error) {
      onLog?.(`扫描控制失败: ${error.message}`);
    }
  }, [ptzApi, deviceId, channelId, scanSettings, onLog, disabled]);

  // 辅助控制
  const handleAuxiliaryControl = useCallback(async (action) => {
    if (!ptzApi || disabled) return;

    try {
      const { switchId, command } = auxiliarySettings;
      let result;

      switch (action) {
        case 'switch':
          result = await ptzApi.auxiliary(deviceId, channelId, command, switchId);
          onLog?.(`辅助开关控制: 开关${switchId} ${command === 'on' ? '开启' : '关闭'}`);
          break;
        case 'wiper_on':
          result = await ptzApi.wiper(deviceId, channelId, 'on');
          onLog?.('雨刷开启');
          break;
        case 'wiper_off':
          result = await ptzApi.wiper(deviceId, channelId, 'off');
          onLog?.('雨刷关闭');
          break;
        default:
          break;
      }
    } catch (error) {
      onLog?.(`辅助控制失败: ${error.message}`);
    }
  }, [ptzApi, deviceId, channelId, auxiliarySettings, onLog, disabled]);

  return (
    <div className={`ptz-advanced ${disabled ? 'disabled' : ''}`}>
      <div className="advanced-header">
        <h4>高级PTZ控制</h4>
      </div>

      {/* 标签页 */}
      <div className="tab-buttons">
        <button
          className={`tab-btn ${activeTab === 'cruise' ? 'active' : ''}`}
          onClick={() => setActiveTab('cruise')}
          disabled={disabled}
        >
          巡航控制
        </button>
        <button
          className={`tab-btn ${activeTab === 'scan' ? 'active' : ''}`}
          onClick={() => setActiveTab('scan')}
          disabled={disabled}
        >
          扫描控制
        </button>
        <button
          className={`tab-btn ${activeTab === 'auxiliary' ? 'active' : ''}`}
          onClick={() => setActiveTab('auxiliary')}
          disabled={disabled}
        >
          辅助控制
        </button>
      </div>

      {/* 巡航控制面板 */}
      {activeTab === 'cruise' && (
        <div className="tab-content">
          <div className="settings-group">
            <div className="setting-item">
              <label>巡航组ID:</label>
              <input
                type="number"
                min="1"
                max="255"
                value={cruiseSettings.cruiseId}
                onChange={(e) => setCruiseSettings(prev => ({
                  ...prev,
                  cruiseId: parseInt(e.target.value) || 1
                }))}
                disabled={disabled}
              />
            </div>
            <div className="setting-item">
              <label>巡航速度:</label>
              <input
                type="number"
                min="1"
                max="255"
                value={cruiseSettings.speed}
                onChange={(e) => setCruiseSettings(prev => ({
                  ...prev,
                  speed: parseInt(e.target.value) || 100
                }))}
                disabled={disabled}
              />
              <button
                onClick={() => handleCruiseControl('setSpeed')}
                disabled={disabled}
                className="set-btn"
              >
                设置
              </button>
            </div>
            <div className="setting-item">
              <label>停留时间(秒):</label>
              <input
                type="number"
                min="1"
                max="3600"
                value={cruiseSettings.time}
                onChange={(e) => setCruiseSettings(prev => ({
                  ...prev,
                  time: parseInt(e.target.value) || 5
                }))}
                disabled={disabled}
              />
              <button
                onClick={() => handleCruiseControl('setTime')}
                disabled={disabled}
                className="set-btn"
              >
                设置
              </button>
            </div>
          </div>
          <div className="control-buttons">
            <button
              onClick={() => handleCruiseControl('start')}
              disabled={disabled}
              className="control-btn start-btn"
            >
              开始巡航
            </button>
            <button
              onClick={() => handleCruiseControl('stop')}
              disabled={disabled}
              className="control-btn stop-btn"
            >
              停止巡航
            </button>
          </div>
        </div>
      )}

      {/* 扫描控制面板 */}
      {activeTab === 'scan' && (
        <div className="tab-content">
          <div className="settings-group">
            <div className="setting-item">
              <label>扫描组ID:</label>
              <input
                type="number"
                min="1"
                max="255"
                value={scanSettings.scanId}
                onChange={(e) => setScanSettings(prev => ({
                  ...prev,
                  scanId: parseInt(e.target.value) || 1
                }))}
                disabled={disabled}
              />
            </div>
            <div className="setting-item">
              <label>扫描速度:</label>
              <input
                type="number"
                min="1"
                max="255"
                value={scanSettings.speed}
                onChange={(e) => setScanSettings(prev => ({
                  ...prev,
                  speed: parseInt(e.target.value) || 100
                }))}
                disabled={disabled}
              />
              <button
                onClick={() => handleScanControl('setSpeed')}
                disabled={disabled}
                className="set-btn"
              >
                设置
              </button>
            </div>
          </div>
          <div className="boundary-controls">
            <div className="boundary-info">
              调整摄像头到要设置的边界位置，然后点击设置边界按钮
            </div>
            <div className="boundary-buttons">
              <button
                onClick={() => handleScanControl('setLeft')}
                disabled={disabled}
                className="boundary-btn"
              >
                设置左边界
              </button>
              <button
                onClick={() => handleScanControl('setRight')}
                disabled={disabled}
                className="boundary-btn"
              >
                设置右边界
              </button>
            </div>
          </div>
          <div className="control-buttons">
            <button
              onClick={() => handleScanControl('start')}
              disabled={disabled}
              className="control-btn start-btn"
            >
              开始扫描
            </button>
            <button
              onClick={() => handleScanControl('stop')}
              disabled={disabled}
              className="control-btn stop-btn"
            >
              停止扫描
            </button>
          </div>
        </div>
      )}

      {/* 辅助控制面板 */}
      {activeTab === 'auxiliary' && (
        <div className="tab-content">
          <div className="auxiliary-section">
            <h5>辅助开关控制</h5>
            <div className="settings-group">
              <div className="setting-item">
                <label>开关ID:</label>
                <input
                  type="number"
                  min="1"
                  max="255"
                  value={auxiliarySettings.switchId}
                  onChange={(e) => setAuxiliarySettings(prev => ({
                    ...prev,
                    switchId: parseInt(e.target.value) || 1
                  }))}
                  disabled={disabled}
                />
              </div>
              <div className="setting-item">
                <label>操作:</label>
                <select
                  value={auxiliarySettings.command}
                  onChange={(e) => setAuxiliarySettings(prev => ({
                    ...prev,
                    command: e.target.value
                  }))}
                  disabled={disabled}
                >
                  <option value="on">开启</option>
                  <option value="off">关闭</option>
                </select>
                <button
                  onClick={() => handleAuxiliaryControl('switch')}
                  disabled={disabled}
                  className="set-btn"
                >
                  执行
                </button>
              </div>
            </div>
          </div>
          <div className="auxiliary-section">
            <h5>雨刷控制</h5>
            <div className="control-buttons">
              <button
                onClick={() => handleAuxiliaryControl('wiper_on')}
                disabled={disabled}
                className="control-btn start-btn"
              >
                雨刷开启
              </button>
              <button
                onClick={() => handleAuxiliaryControl('wiper_off')}
                disabled={disabled}
                className="control-btn stop-btn"
              >
                雨刷关闭
              </button>
            </div>
          </div>
        </div>
      )}

      <style jsx>{`
        .ptz-advanced {
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          padding: 16px;
          margin: 16px 0;
          max-width: 400px;
        }

        .ptz-advanced.disabled {
          opacity: 0.6;
          pointer-events: none;
        }

        .advanced-header h4 {
          margin: 0 0 16px 0;
          color: #343a40;
          font-size: 16px;
          text-align: center;
        }

        .tab-buttons {
          display: flex;
          margin-bottom: 16px;
          border-bottom: 1px solid #dee2e6;
        }

        .tab-btn {
          flex: 1;
          padding: 8px 12px;
          border: none;
          background: transparent;
          color: #6c757d;
          cursor: pointer;
          font-size: 12px;
          border-bottom: 2px solid transparent;
          transition: all 0.2s;
        }

        .tab-btn:hover {
          background: #e9ecef;
          color: #495057;
        }

        .tab-btn.active {
          color: #007bff;
          border-bottom-color: #007bff;
          background: #e3f2fd;
        }

        .tab-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .tab-content {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .settings-group {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .setting-item {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
        }

        .setting-item label {
          min-width: 80px;
          color: #495057;
          font-weight: 500;
        }

        .setting-item input,
        .setting-item select {
          flex: 1;
          padding: 4px 8px;
          border: 1px solid #ced4da;
          border-radius: 4px;
          font-size: 12px;
        }

        .set-btn {
          padding: 4px 12px;
          background: #28a745;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .set-btn:hover {
          background: #218838;
        }

        .set-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .control-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;
        }

        .control-btn {
          padding: 8px 16px;
          border: none;
          border-radius: 4px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s;
          min-width: 80px;
        }

        .start-btn {
          background: #28a745;
          color: white;
        }

        .start-btn:hover {
          background: #218838;
        }

        .stop-btn {
          background: #dc3545;
          color: white;
        }

        .stop-btn:hover {
          background: #c82333;
        }

        .control-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .boundary-controls {
          background: #fff3cd;
          border: 1px solid #ffeaa7;
          border-radius: 4px;
          padding: 12px;
        }

        .boundary-info {
          font-size: 12px;
          color: #856404;
          margin-bottom: 8px;
          text-align: center;
        }

        .boundary-buttons {
          display: flex;
          gap: 8px;
          justify-content: center;
        }

        .boundary-btn {
          padding: 6px 12px;
          background: #ffc107;
          color: #212529;
          border: none;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .boundary-btn:hover {
          background: #e0a800;
        }

        .boundary-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .auxiliary-section {
          background: #ffffff;
          border: 1px solid #dee2e6;
          border-radius: 4px;
          padding: 12px;
        }

        .auxiliary-section h5 {
          margin: 0 0 8px 0;
          font-size: 14px;
          color: #495057;
        }
      `}</style>
    </div>
  );
}